﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZdSoft.Core;
using ZdSoft.IDAL;
using System.Web.UI;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using ZdSoft.Web.OnlineStudy.Apps;
using NHibernate.Criterion;
using ZdSoft.Model;
using ZdSoft.BLL;
using System.Data;
using System.Web.Script.Serialization;
using System.IO;

namespace ZdSoft.Web.OnlineStudy.Controllers
{
    public class UserController : BaseController
    {
        #region 获取注册账号是否存在
        public JsonResult UserIsExite(string account)
        {
            IList<ICriterion> query = new List<ICriterion>();
            query.Add(new LikeExpression("Account", account));
            bool user = Container.Instance.Resolve<IUserDAL>().Exists(query);
            return Json(new { statu = user }, JsonRequestBehavior.AllowGet);
        }


        #endregion


        #region 注册
        [HttpGet]
        public ViewResult Register()
        {
            Model.User model = new User();
            return View(model);
        }
        [HttpPost]
        public JsonResult Register(string account, string username, string password)
        {
            try
            {
                Model.User users = new Model.User();
                users.Password = AppHelper.EncodeMd5(password);
                users.Account = account;
                users.UserName = username;
                users.IsActive = true;//默认注册都为可用
                Container.Instance.Resolve<IUserDAL>().Create(users);
                return Json(new { statu = true });
            }
            catch (Exception ex)
            {
                return Json(new { statu = ex.Message });
            }

        }
        #endregion
        #region 登录
        [HttpGet]
        public ViewResult Login()
        {
            Model.User model = new User();
            model.Account = "admin";//为了开发调试
            model.Password = "123456";
            return View(model);
        }

        [HttpPost]
        public ActionResult Login(User model)
        {
            model.Password = AppHelper.EncodeMd5(model.Password);//用MD5加密
            //访问数据库，根据用户名和密码获取用户信息
            IUserDAL userService = Container.Instance.Resolve<IUserDAL>();
            Model.User loginedUser = userService.Login(model.Account, model.Password);
            if (loginedUser != null)//当用户名和密码正确时
            {
                //保存用户登录信息
                AppHelper.LoginedUser = loginedUser;
                //获取当前登录对象的角色信息，待用
                //IList<Role> roleList = loginedUser.Roles;

                //页面跳转到主页面
                return RedirectToAction("Index", "Home");
            }
            else
            {
                //如果登录不成功，则向用户提示错误信息
                ViewBag.ErrorMsg = "用户名或密码错误。";
                return View(model);
            }
        }

        [HttpGet]
        public ViewResult Index()
        {
            IList<User> listUser = Container.Instance.Resolve<IUserDAL>().GetAll();
            ViewBag.userCount = listUser.Count;
            var query = listUser.Skip(0).Take(10).ToList();
            return View(query);
        }
        #endregion
        [HttpPost]
        public JsonResult Index(int pageSize,int pageIndex)
        {
            DataTable dt = Container.Instance.Resolve<IUserDAL>().GetPaged(10, pageIndex);
            IList<User> listUser=ZdSoft.Web.OnlineStudy.Apps.ModelConvertHelper<User>.ConvertToModel(dt);
            JavaScriptSerializer js=new JavaScriptSerializer();
            string jsonStr= js.Serialize(listUser);
            return Json(jsonStr);
        }

        [HttpGet]
        public ViewResult Create()
        {
            //实例化模型对象
            User user = new User();
            //准备视图需要的角色信息
            SetRoles();
            return View(user);
        }

        private void SetRoles()
        {
            IList<Role> roleList = Container.Instance.Resolve<IRoleDAL>().GetAll()
                .Where(m => m.IsActive == true)
                .ToList();
            ViewBag.RoleList = roleList;
        }
        /// <summary>
        /// 提交创建的用户
        /// 说明;获取表单值的方法如下
        /// 1、表示获取model对象，将model对象作为参数，可获取对象的所有值
        /// 2：表示获取指定控件的值，将控件名称(控件的name属性）作为参数，可获取该控件的值
        /// </summary>
        /// <param name="user"></param>
        /// <param name="hdSelectedIds"></param>
        /// <returns></returns>
        [HttpPost]

        public ActionResult Create(User user, string hdSelectedIds)
        {
            //确定模型验证是否通过
            //user.Password = Container.Instance.Resolve<ISystemSettingService>().GetDefaultPassword();//获取系统默认的密码
            if (ModelState.IsValid)
            {
                //判断是否存在
                if (Container.Instance.Resolve<IUserDAL>().AccountCheck(0, user.Account))
                {
                    ModelState.AddModelError("Account", "账号已经存在");//返回提示信息
                    SetRoles();//提供角色试图显示
                    return View(user);
                }
                Container.Instance.Resolve<IUserDAL>().Create(user, hdSelectedIds.Replace(",,", ","));
                return RedirectToAction("Index");
            }
            SetRoles();
            return View(user);//停留在原始页面
        }

        public ActionResult Delete(int userID)
        {
            try
            {
                Container.Instance.Resolve<IUserDAL>().Delete(userID);
                return Redirect("http://localhost:24833/User");
            }
            catch
            {
                return Redirect("http://localhost:24833/User");
            }
        }


        [HttpGet]
        public ActionResult Edit(int id)
        {
            //根据角色信息ID查询角色信息
            Role model = Container.Instance.Resolve<IRoleDAL>().Get(id);
            //以模型传值得方式将model传递到Create视图中显示
            return View("Create", model);
        }
        [HttpPost]
        public ActionResult Edit(Role model)
        {
            if (ModelState.IsValid)
            {
                Container.Instance.Resolve<IRoleDAL>().Update(model);

                return RedirectToAction("Index");
            }
            return View("Create", model);//停留在当前页面
        }
        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="id">角色id</param>
        /// <returns></returns>
        public ActionResult SwitchStatus(int id)
        {
            Role model = Container.Instance.Resolve<IRoleDAL>().Get(id);

            model.IsActive = !model.IsActive;//操作一次就取反一次

            Container.Instance.Resolve<IRoleDAL>().Update(model);
            return RedirectToAction("Index");//返回到主页
        }
        [HttpGet]
        public ViewResult AssignRole(int id)
        {
            User user = Container.Instance.Resolve<IUserDAL>().Get(id);

            IList<Role> roleList = Container.Instance.Resolve<IRoleDAL>().GetAll().Where(m => m.IsActive == true).ToList();
            if (user.Roles != null)
            {
                foreach (var item in roleList)
                {
                    if (user.Roles.Where(m => m.ID == item.ID).Count() > 0)
                    {
                        item.IsChecked = true;
                    }
                }
            }
            ViewBag.RoleList = roleList;
            return View(user);
        }
        [HttpPost]
        public ActionResult AssignRole(int userId, string hdSelectedIds)
        {
            Container.Instance.Resolve<IUserDAL>().AssignRole(userId, hdSelectedIds.Replace(",,", ","));
            return RedirectToAction("Index");
        }
        [HttpPost]
        public void Exite()
        {
            ZdSoft.Web.OnlineStudy.Apps.AppHelper.LoginedUser = null;
        }
    }
}
